$(function(){
		
	var userTable = function(){
		return matchTable('#datatables','/user/listData.do',listArr, function(obj){
			obj.loginNameSearch = $("#loginNameSearch").val();
			obj.userNameSearch = $("#userNameSearch").val();
			obj.roleSearch = $("#roleSearch").val();
		},true);
	}
	
	userTable();
	
	ajaxSer.userRoleInit(function(data){
		var liList = "";
		var userData = data.data;
		for(var i=0; i<userData.length; i++){
			liList += '<li><label style="text-align:left;"><input type="checkbox" id="'+ userData[i].id +'">  '+ userData[i].sysRoleName  +'</label></li>';
		}
		$(".roletouser ul").append(liList);
	});
	
	//查询
	$(".vdrallsearch").on('click',function(){
		userTable().draw();
	});
	
	//新增
	$(".useradd").on('click',function(){
		layer.open({
	    	  title: '新增', 
			  skin: 'demo-class',
			  area: ['650px', '400px'],
			  btn: ['确认', '取消'],
			  content: $(".userform").html(),
			  success: function(layero, index){
				  
				    $(layero).find('#adduserdio').validate({
				    	rules: {
					    	confirm_password:{
						        equalTo: $(layero).find('#adduserdio').find("#password")
						    }
				    	}
				    });
				    
			  },
			  yes:function(index, layero){
				  //这里是回调，点击确认的时候执行的方法，最后一个关闭需要手动调用
				  if($(layero).find('#adduserdio').valid()){
					  
					  $.ajax({
						  url : webroot+'/user/whetherUsernameExist.ajax',
						  data : {'loginName':$(layero).find('#loginName').val(),'userId':''},
						  type : 'POST',
						  dataType : 'json',
						  success : function(data){
							  if(data.type == '2'){
								  if(data.resultMap.result>0){
									  layer.msg('添加失败，登入名重复');
								  }else{
									  noClick(layero);
									  var roleList = [67];
									  roleList = roleList.join();
									  var userListTree = $.extend({},{'roleIds':roleList},$(layero).find('form').serializeObject());
									  ajaxSer.userAdd(userListTree, function(data){
										  hasClick(layero);
										  if(data.type == "2"){
											 userTable().draw();
										  }
										  layer.msg(data.msg);
									  },function(){
										  hasClick(layero);
									  })
									  layer.close(index);
								  }
							  }else{
								  layer.msg('添加失败，系统发生内部不错误');
							  }
						  }
					  })
					  
				  }
			  },
			  cancel:function(index){
				  layer.close(index);
			  }
			});
	});
	
	//修改
	$(".useredit").on('click',function(){
		var choose_a = $('#datatables tbody :checkbox:checked');
        var c_tIds;
        c_tIds = choose_a.eq(0).val();
        if (c_tIds == undefined || $.trim(c_tIds) == "") {
        	layer.msg("请选择一条记录！");
            return false;
        }
        if(choose_a.length != 1){
        	layer.msg("只能选择一条记录！");
            return false;
        }
    	layer.open({
    	  title: '修改', 
  		  skin: 'demo-class',
  		  area: ['650px', '400px'],
  		  btn: ['确认', '取消'],
  		  content: $(".userform").html(),
  		  success: function(layero, index){
  			//修改之前执行填充操作
  			$(layero).find('#adduserdio').validate({
		    	rules: {
			    	confirm_password:{
				        equalTo: $(layero).find('#adduserdio').find("#password")
				    }
		    	}
		    });
  			
  			ajaxSer.userEditBefore(c_tIds,function(data){
  				var nameVal = $(layero).find('form input');
				for(var i=0; i<nameVal.length;i++){
					if(data[$(nameVal[i]).attr('name')]){
						$(nameVal[i]).val(data[$(nameVal[i]).attr('name')])
					}
				}
				
				$(layero).find("#confirm_password").val(data.password);
				
  			})
  			
  		  },
  		  yes:function(index, layero){
  			if($(layero).find('#adduserdio').valid()){
  				$.ajax({
					  url : webroot+'/user/whetherUsernameExist.ajax',
					  data : {'loginName':$(layero).find('#loginName').val(),'userId':c_tIds},
					  type : 'POST',
					  dataType : 'json',
					  success : function(data){
						  if(data.type == '2'){
							  if(data.resultMap.result>0){
								  layer.msg('修改失败，登入名重复');
							  }else{
								  noClick(layero);
								    var roleList = [67];
								    roleList = roleList.join();
								    
						  			var treeJson = $.extend({},{'id':c_tIds,'roleIds':roleList},$(layero).find('form').serializeObject());
						  			
						  			ajaxSer.userEdit(treeJson, function(data){
						  				hasClick(layero);
						  				if(data.type == "2"){
						  					userTable().draw();
										}
										layer.msg(data.msg);
						  			},function(){
						  				hasClick(layero);
						  			})
						  			layer.close(index);
							  }
						  }else{
							  layer.msg('修改失败，系统发生内部不错误');
						  }
					  }
				  })
  				
  			}
  		  },
  		  cancel:function(index){
  			  layer.close(index);
  		  }
  		});
	});
	
	//删除
	$(".userdel").on('click',function(){
		
		var del_tIds = "";
        var data_a = $("#datatables tbody :checkbox:checked");
        $.each(data_a, function (n) {
            if (n == 0) {
                del_tIds = data_a.eq(n).val();
            } else {
                del_tIds = del_tIds + "," + data_a.eq(n).val();
            }
        })
        if (del_tIds == undefined || $.trim(del_tIds) == "") {
        	layer.msg("请选择一条记录！");
            return false;
        }
    	layer.confirm('确认删除?', {icon: 3, title:'删除'}, function(index){
    		var delTree = {
    				'uIds':del_tIds,
    				'method':'delete'
    		}
    		ajaxSer.userDel(delTree, function(data){
    			if(data.type == "2"){
					userTable().draw();
				}
				layer.msg(data.msg);
    		})
		    layer.close(index);
		});
		
	});
	
	
	//单击行选中事件
    $('#datatables tbody').on('click', 'tr', function () {
        var table = $('#datatables').DataTable();
        var data = table.row(this).data();
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            $('#check' + data.id).prop("checked", false);
        } else {
            $(this).addClass('selected');
            $('#check' + data.id).prop("checked", true);
        }
    });
    //全选
    $(".checkall").click(function () {
        var check = $(this).prop("checked");
        $(".checkchild").prop("checked", check);
        var cells = new Array();
        $('#datatables tbody tr').each(function () {
            if (check) {
                $(this).addClass('selected');
            } else {
                $(this).removeClass('selected');
            }
        });
    });
});

function userOn(str,e){
	e.stopPropagation();
	var states = "";
	if(e.srcElement.innerHTML == "启用"){
		states = "disable";
		e.srcElement.innerHTML = "禁用";
	}else{
		states = "enable";
		e.srcElement.innerHTML = "启用";
	}
	var params = {"uIds":str,"method":states};
	
	ajaxSer.userOnOff(params, function(data){
		console.log(data);
	});
}